// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameEvent from "../Commons/GameEvent";
import PlatformManager from "../Platforms/PlatformManager";
import AccountData from "../Saves/AccountData";
import PlayerSaveData from "../Saves/PlayerSaveData";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SaveManager extends cc.Component {

    private static readonly USER_DATA: string = "user_data";

    private static _single: SaveManager;
    public userdata: PlayerSaveData;
    public roleId: number;

    public accountData: AccountData = new AccountData();
    private _age: number = 0;
    public chatMessageList: any[] = [];
    public get age(): number {
        return this._age;
    }
    public set age(value: number) {
        this._age = value;
    }
    public token: string;
    /**服务器存档数据 */
    public cloudSaveData: string = null;
    public static get single(): SaveManager {
        return SaveManager._single;
    }

    protected onLoad(): void {
        if (SaveManager._single == null) {
            SaveManager._single = this;
        } else {
            this.node.destroy();
            this.node.removeFromParent();
        }

        cc.game.addPersistRootNode(this.node);
        this.userdata = new PlayerSaveData();

        var that = this;
        window.onunload = () => {
            that.logoutGame();
        }
    }
    public initUserData() {
        this.userdata.initUserData();
        this.saveData();
    }

    public saveData(): void {
        // console.log("存档", JSON.stringify(this.userdata));
        cc.sys.localStorage.setItem(SaveManager.USER_DATA, JSON.stringify(this.userdata));
    }

    public loadData() {
        // if (!SaveManager.single.isHavSaveData()) {
        //     this.initUserData();
        // }
        var data: any;
        if (this.cloudSaveData != null) {
            data = JSON.parse(this.cloudSaveData);
        } else {
            this.initUserData();
            data = JSON.parse(cc.sys.localStorage.getItem(SaveManager.USER_DATA));
        }
        this.userdata.loadData(data);
    }

    public isHavSaveData(): boolean {
        var data = cc.sys.localStorage.getItem(SaveManager.USER_DATA)
        return data != null;
    }

    isEnoughGold(cost: number): boolean {
        return this.userdata.gold >= cost;
    }

    isEnoughDiamond(cost: number): boolean {
        return this.userdata.diamond >= cost;
    }
    changeAddSpeedMode() {
        this.userdata.addSpeedMode++;
        this.userdata.addSpeedMode = this.userdata.addSpeedMode > 2 ? 0 : this.userdata.addSpeedMode;
        GameEvent.eventNode.emit(GameEvent.CHANGEADDSPEEDMODE_EVENT);
    }
    changeName() {
        this.userdata.isFirstChangeName = false;
    }

    updataGuideId() {
        this.userdata.guideId++;
        this.saveData();
        GameEvent.eventNode.emit(GameEvent.UPDATAGUIDE_EVENT);
    }
    /**上报游戏数据 */
    async gameDataReport() {
        var sdk = PlatformManager.single.basePlatform.sdk;
        let result = await sdk.gameDataReport(SaveManager.single.accountData.username, [JSON.stringify(this.userdata)]);
        if (result.code == 200) {
            console.log('游戏数据上报成功', result)
        } else {
            console.log('游戏数据上报失败', result)
        }
    }
    async logoutGame() {
        var sdk = PlatformManager.single.basePlatform.sdk;
        let result = await sdk.logout(SaveManager.single.accountData.username);
        if (result.code == 200) {
            console.log('退出成功', result)
        } else {
            console.log('退出失败', result)
        }
    }

    async getGameNickname() {
        if (this.userdata.isFirstSetName == false) {
            var sdk = PlatformManager.single.basePlatform.sdk;
            let result = await sdk.getGameNickname();
            if (result.code == 200) {
                this.userdata.playerName = result.data.nickName;
                this.userdata.isFirstSetName = true;
                this.saveData();
                GameEvent.eventNode.emit(GameEvent.RENAME_EVENT);
            }
        }
    }

    async getChatMessage() {
        var sdk = PlatformManager.single.basePlatform.sdk;

        let result = await sdk.getChatMessage();
        if (result.code == 200) {
            this.chatMessageList = result.data.chatMessageList;
            GameEvent.eventNode.emit(GameEvent.UPDATACHATMESSAGE_EVENT);

        }
    }


}
